package com.zxp.mall.order.listener;


import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.zxp.mall.order.config.AlipayTemplate;
import com.zxp.mall.order.service.OrderService;
import com.zxp.mall.order.vo.PayAsyncVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

//http://member.gulimall.com/memberOrder.html
// ?charset=utf-8&out_trade_no=202403211251322751770674580860534785
// &method=alipay.trade.page.pay.return
// &total_amount=203.00
// &sign=TgprRm09ONgbhx3o%2FVh5q%2FoqUm7Ijt1ua2skf7yYWB9PC335xM3QbgwpWP13%2B3F1m%2FS6VPP6KDENCoVLwRRMBm1cg5zrRAM6NdaFQ5Q2WTcC8g66GrfN9SOlMdzv%2Fe%2Bglgqoaxg%2F%2FZ%2FusbJMXT7eKLiAu2dUPXZ4Xxq1EgibAVgPWdc4XiDKaHqmvo4iEE0qgwqOYm5mHIw57SF9puiUy0P5USUr2VqO4BuFdgtFDqFE%2BP7bnK8oUUyVBb4vFr%2Bxk9mm3UJw%2B%2F20wT%2FCR5cDy7Zvug1p9zQkvJBGM23gvMrIrVA5Mk4lPjZBXjVx%2BAtUYwnxDQnRRBDA6U1IPILeMQ%3D%3D&trade_no=2024032122001482260502522893&auth_app_id=9021000135648432&version=1.0&app_id=9021000135648432&sign_type=RSA2&seller_id=2088721032182251&timestamp=2024-03-21+12%3A52%3A14

@RestController
public class OrderPayedListener {

    @Autowired
    OrderService orderService;

    @Autowired
    AlipayTemplate alipayTemplate;

    @PostMapping("/payed/notify")
    public String handleAliPayed(PayAsyncVo payAsyncVo, HttpServletRequest request) throws UnsupportedEncodingException, AlipayApiException {
//        Map<String, String[]> map = request.getParameterMap();
//        支付宝异步通知  返回success 支付宝就不会再通知了
        System.out.println("支付宝通知到了" );
//        System.out.println("支付宝通知到了" + map);
//        Set<String> keys = map.keySet();
//        for (String key : keys) {
//            System.out.println(key + "->" + map.get(key));
//        }

//        验证签名
        //获取支付宝POST过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
//            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }

        boolean signVerified = AlipaySignature.rsaCheckV1(params, alipayTemplate.alipay_public_key, alipayTemplate.getCharset(),
                alipayTemplate.getSign_type()); //调用SDK验证签名

        //——请在这里编写您的程序（以下代码仅作参考）——

	/* 实际验证过程建议商户务必添加以下校验：
	1、需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号，
	2、判断total_amount是否确实为该订单的实际金额（即商户订单创建时的金额），
	3、校验通知中的seller_id（或者seller_email) 是否为out_trade_no这笔单据的对应的操作方（有的时候，一个商户可能有多个seller_id/seller_email）
	4、验证app_id是否为该商户本身。
	*/
        if(signVerified) {//验证成功
            System.out.println("签名验证成功");
        String result = orderService.handlePayResult(payAsyncVo);
        return result;
        }else{
            System.out.println("签名验证shibai");
            return "error";
        }
    }

}
